package com.tbk.wechatbot.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tbk.wechatbot.util.RestTemplateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
public class TpwdService {

    @Autowired
    private RestTemplateUtil restTemplateUtil;

    @Value("${material.tpwd.url}")
    private String materialTpwdUrl;

    public List<String> getMaterialTpwd(String q) {
        String url = this.materialTpwdUrl + "?q=" + q;
        String materialTpwd = restTemplateUtil.stringRestGet(url);

        JSONObject materialTpwdJsonObj = JSON.parseObject(materialTpwd);
        List<String> tpwdList = this.processMaterialTpwd(materialTpwdJsonObj);
        return tpwdList;
    }


    private List<String> processMaterialTpwd(JSONObject materialTpwdJsonObj) {
        if (materialTpwdJsonObj.containsKey("error")) {
            return null;
        }
        List<String> tpwdList = new ArrayList<>();
        JSONArray materialTpwdJsonArr = materialTpwdJsonObj.getJSONArray("tpwd_list");
        for (int i = 0; i < materialTpwdJsonArr.size(); i++) {
            JSONObject tpwdJsonObj = materialTpwdJsonArr.getJSONObject(i);
            String tpwd = tpwdJsonObj.getString("tpwd_str");
            tpwdList.add(tpwd);
        }
        return tpwdList;
    }


}
